var async = require("async");
var _ = require("lodash");
var siteInfoService = require("../services/site-info.service");
var categoriesService = require("../services/categories.service");
var listsService = require("../services/lists.service");
//获取page 或者 content服务
var contentsService = require("../services/contents.service");
var pagesService = require("../services/pages.service");

/**
 * 频道
 * @param {Object} req
 * @param {Object} res
 * @param {Function} next
 */
module.exports = function (req, res, next) {
  var channelPath = "/" + req.params.channel + req.params[0];
  categoriesService.one(
    {
      path: channelPath,
      type: "channel",
    },
    function (err, category) {
      if (err) return res.status(500).end();

      if (!category) return next();

      async.parallel(
        {
          siteInfo: siteInfoService.get,
          navigation: function (callback) {
            categoriesService.navigation({ current: channelPath }, callback);
          },
          lists: function (callback) {
            listsService.channel(category, callback);
          },
          localReadingTotal: function (callback) {
            listsService.reading({ path: channelPath }, callback);
          },
          localReadingDay: function (callback) {
            listsService.reading(
              { path: channelPath, sort: "-reading.day" },
              callback
            );
          },
          localReadingWeek: function (callback) {
            listsService.reading(
              { path: channelPath, sort: "-reading.week" },
              callback
            );
          },
          localReadingMonth: function (callback) {
            listsService.reading(
              { path: channelPath, sort: "-reading.month" },
              callback
            );
          },
        },
        function (err, results) {
          if (err) return res.status(500).end();
          let { navigation, lists } = results;
          //获取页面默认展示文章保留参数
          let channeldefault, pageParams, contentParam, contentParam2;
          // 遍历导航 将栏目内容从lists取来添加 获得需要的导航栏

          navigation.map((e) => {
            if (e.current) {
              let temp = e;
              temp.nodes &&
                temp.nodes.map((i, index) => {
                  if (i.type == "column") {
                    i.column = true
                    lists.forEach((j) => {
                      if (j.name == i.name) {
                        i.contents = j.contents;
                      }
                    });
                    if (index == 0) {
                      if (i.contents.length) {
                        let params = i.contents[0].href;
                        contentParam = _(params).split("/").last();
                        contentParam2 = params.split("/").slice(0, 3).join("/");
                      }
                    }
                    return i;
                  } else {
                    if (index == 0) {
                      pageParams = i.path;
                    }
                    return i;
                  }
                });
              return temp;
            } else {
              return e;
            }
          });
          results.navigation = navigation;
          //放到全局
          global.navigation = navigation;

          if (contentParam) {
            contentsService.one(
              {
                alias: contentParam,
              },
              function (err, content) {
                if (err) return res.status(500).end();

                if (!content) return next();

                var categoryPath = contentParam2;

                async.auto(
                  {
                    siteInfo: siteInfoService.get,
                    navigation: function (callback) {
                      categoriesService.navigation(
                        { current: categoryPath },
                        callback
                      );
                    },
                    category: function (callback) {
                      categoriesService.one(
                        {
                          path: categoryPath,
                          type: "column",
                        },
                        function (err, category) {
                          if (err) return callback(err);
                          if (!category) return callback("没有找到 Category");

                          callback(null, category);
                        }
                      );
                    },
                    localReadingTotal: [
                      "category",
                      function (callback, result) {
                        listsService.reading(
                          { _id: result.category._id },
                          callback
                        );
                      },
                    ],
                    localReadingDay: [
                      "category",
                      function (callback, result) {
                        listsService.reading(
                          {
                            _id: result.category._id,
                            sort: "-reading.day",
                          },
                          callback
                        );
                      },
                    ],
                    localReadingWeek: [
                      "category",
                      function (callback, result) {
                        listsService.reading(
                          {
                            _id: result.category._id,
                            sort: "-reading.week",
                          },
                          callback
                        );
                      },
                    ],
                    localReadingMonth: [
                      "category",
                      function (callback, result) {
                        listsService.reading(
                          {
                            _id: result.category._id,
                            sort: "-reading.month",
                          },
                          callback
                        );
                      },
                    ],
                  },
                  function (err, result) {
                    if (err && !result.category) return next();
                    if (err) return res.status(500).end();
                    channeldefault = content.content;
                    res.render(_.get(category, "views.channel"), {
                      layout: _.get(category, "views.layout"),
                      siteInfo: results.siteInfo,
                      navigation: results.navigation,
                      category: category,
                      lists: results.lists,
                      channeldefault: channeldefault,
                      readingList: {
                        total: results.localReadingTotal,
                        day: results.localReadingDay,
                        week: results.localReadingWeek,
                        month: results.localReadingMonth,
                      },
                    });
                  }
                );
              }
            );
          }
          if (pageParams) {
            pagesService.one(
              {
                path: pageParams,
              },
              function (err, page) {
                if (err) return res.status(500).end();

                if (!page) return next();

                // 读取单页所需数据
                async.parallel(
                  {
                    siteInfo: siteInfoService.get,
                    navigation: function (callback) {
                      categoriesService.navigation(
                        { current: page.path },
                        callback
                      );
                    },
                  },
                  function (err, result) {
                    channeldefault = page.mixed.pageContent;
                    res.render(_.get(category, "views.channel"), {
                      layout: _.get(category, "views.layout"),
                      siteInfo: results.siteInfo,
                      navigation: results.navigation,
                      category: category,
                      lists: results.lists,
                      channeldefault: channeldefault,
                      readingList: {
                        total: results.localReadingTotal,
                        day: results.localReadingDay,
                        week: results.localReadingWeek,
                        month: results.localReadingMonth,
                      },
                    });
                  }
                );
              }
            );
          }
          if (!pageParams & !contentParam) {
            channeldefault = "";
            res.render(_.get(category, "views.channel"), {
              layout: _.get(category, "views.layout"),
              siteInfo: results.siteInfo,
              navigation: results.navigation,
              category: category,
              lists: results.lists,
              channeldefault: channeldefault,
              readingList: {
                total: results.localReadingTotal,
                day: results.localReadingDay,
                week: results.localReadingWeek,
                month: results.localReadingMonth,
              },
            });
          }
        }
      );
    }
  );
};
